function checkData(checkDomTxt, executeNum, callback, maxNum = 10) {
  if (executeNum >= maxNum) {
    console.log('100秒过去了，但没有检查到内容')
    return
  }
  setTimeout(() => {
    if (!!document.querySelector(checkDomTxt)) {
      callback()
    } else {
      checkData(checkDomTxt, executeNum + 1, callback, maxNum)
    }
  }, 1000);
}


function fetchAmazonDetailDataFromPage(document){
    var dataPro = {};
    var pics = [];
    document.find("body").find(".a-spacing-small.item.imageThumbnail").each(function(e){
        pics.push($(this).find("img").attr("src"));
    })
    dataPro.pics = pics;//图片

    document.find("script").each(function(e){

        var scriptData = $(this).html();
        //console.log(scriptData);
        if(scriptData.indexOf('var obj = A.$.parseJSON') !== -1){
                console.log("match到了 A.$.parseJSON");
                var regex = /A\.(\$\.)?parseJSON\(['"]([\s\S]*)['"]\)/;
                var match = scriptData.match(regex);
                console.log(match);
                if (match) {
                  try {
                      var matchData = match[2].replace(/\\/g, '');
                      var jsonObj = JSON.parse(matchData);
                      var vidlist=jsonObj.videos;
                      console.log(vidlist); // 打印出解析后的 JavaScript 对象
                      var videos = [];
                      for (var i = 0; i < vidlist.length; i++) {
                        var vidUrl = vidlist[i].url;
                        console.log("url["+i+"]是：" + vidUrl);
                            videos.push(vidUrl)
                      }
                      dataPro.videos = videos;
                    } catch (error) {
                      console.error('Invalid JSON:', error);
                    }

                }
        }

        if (scriptData.indexOf("'colorImages'") !== -1) {
           console.log("字符串中包含 'world'");
           //console.log(scriptData);
           var pattern = /'colorImages': \s*(\{[\s\S]*?\}),\n/m; // 匹配 var data = {...}; 的正则表达式
           var match = scriptData.match(pattern); // 在代码块中查找 var data = {...}; 的匹配结果
            console.log(match);
            if (match) {
              var dataStr = match[1].replace(/'/g, '"');; // 取出匹配到的 {...} 部分

              var dataObj = JSON.parse(dataStr); // 将 {...} 解析为 JSON 对象
               console.log(dataObj.initial);
              var picsNew = [];
              for (var element of dataObj.initial) {
                  if(element['hiRes']){
                    picsNew.push(element['hiRes'])
                  }else if(element['large']){
                     picsNew.push(element['large'])
                  }
             }
            console.log(picsNew);
            if(picsNew.length>0){
                dataPro.pics= picsNew;
            }
           }
        }
    })


    dataPro.detail = document.find(".a-unordered-list.a-vertical.a-spacing-mini").html();
    dataPro.content = document.find("#witb-content-list").html();
    dataPro.price =  $(".a-price").find(".a-offscreen").html();
    var cates = [];
    document.find(".a-link-normal.a-color-tertiary").each(function(e){
         var catesItem = {};
         catesItem.amazon_cate_name = $(this).html();
         catesItem.amazon_cate_link = $(this).attr("href");
         cates.push(catesItem);
    });
    dataPro.cates = cates;


    var descList = [];
    document.find(".celwidget.aplus-module.aplus-standard").each(function(e){
            var descItem = $(this).html();
            console.log("++++++")
            console.log(descItem)
            descList.push(descItem);
     });
     if(descList.length===0){

        console.log($("h2:contains('Product Description')").html);
        $("h2:contains('Product Description')").next("div").find(".celwidget:not([cel_widget_id$=\"video\"])").each(function(e){
                var descItem = $(this).html();
                console.log("++++++")
                console.log(descItem)
                descList.push(descItem);
         });
     }

     console.log(descList);
     if(descList){
        dataPro.desc = descList.join("######");
     }

    if(document.find("#productDescription").html() && document.find("#productDescription").html().length>500){
        dataPro.desc += document.find("#productDescription").html();
        console.log("desc append #productDescription");
    }

    dataPro.seller = document.find("#sellerProfileTriggerId").html();
    dataPro.seller_url = document.find("#sellerProfileTriggerId").attr("href");

    if(!dataPro.seller){
        dataPro.seller = $(".a-size-small.tabular-buybox-text-message").eq(1).html()
        dataPro.seller_url = "";
        if(!dataPro.seller){
            dataPro.seller = "default";
        }
    }
    console.log(dataPro.seller);

    var attrs = [];
     document.find("#prodDetails").find("tr").each(function(e){
        var attrKey = $(this).find("th").html();
        var attrValue = $(this).find("td").html();
        var attr = {};
        attr.key = attrKey;
        attr.value = attrValue;
        attrs.push(attr);
    })
    if(attrs.length==0){
        document.find("#detailBullets_feature_div").find(".a-list-item").each(function(e){
            var attrKey = $(this).find("span").html();
            var attrValue = $(this).find("span:eq(1)").html();
            var attr = {};
            attr.key = attrKey;
            attr.value = attrValue;
            attrs.push(attr);
        })
    }
    dataPro.attrs = attrs;
    dataPro.path = location.href;
    dataPro.title = document.find("#productTitle").html();
    console.log(dataPro);
    return dataPro;
}

function fetchAmazonDetailData(document){
    var dataPro = fetchAmazonDetailDataFromPage(document);
    $.post("https://www.gongrenbao.cn/index.php?c=api/ozon/updateaamazondetail",
          {dataPro:dataPro},
          function(data){
            console.log(data);
          },
      "text");
}


function getQueryString(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return r[2];
    };
    return 0;
 }
/*
function getFirstPage(){
    var text = getQueryString("text");
    var category = getQueryString("category");
    var get_max_page = getQueryString("get_max_page");
    $.get("https://www.gongrenbao.cn/index.php?c=api/ozon/getozonsearchqdetail&q="+text+"&cate="+category,
      function(data){
            console.log(data);
            var dataobj = JSON.parse(data);
            get_max_page = dataobj.data.get_max_page;
            updateFirstPageByDom($("body"),text,category,get_max_page);
      },
  "text").fail(function(xhr, error) {
            // 处理错误的回调函数
            console.log(xhr.statusText);
            console.log(error);
            setTimeout(function() {
                getFirstPage();
        }, 20000);
    });

}*/

function updateFirstPageByDom(dom,text,category,get_max_page,sku_id){
    var noresult = false;
    var tf_state = "";
    var body = "";
    dom.find("div").each(function(e){
        var indexid=$(this).attr("id")+"";
        if (indexid.indexOf("searchResultsV2-") != -1 ){
            console.log($(this).attr("id"));
            body = $(this).attr("data-state");
        }
        if (indexid.indexOf("state-megaPaginator") != -1 ){
             var megaPaginatorData = $(this).attr("data-state");
             console.log(megaPaginatorData);
             const regex = /tf_state=(.*?)[\"'<>` &;]/;
             const match = megaPaginatorData.match(regex);
             console.log(match);
             if(match && match[1]){
                tf_state = match[1];
             }
        }
        if(indexid.indexOf("state-searchResultsError-") != -1){
            noresult = true;
        }
    });
    console.log("noresult:"+noresult);
    var itemCount = 0;
    if(noresult==true){
        itemCount=0;
    }else if(body){
        var bodyObj = JSON.parse(body);
        var itemCount = bodyObj.items.length;
    }else{
        //没有结果并且noresult也没有拿到，应该是被拦截了
        console.log("没有结果并且noresult也没有拿到，可能是被拦截了，尝试下一个Q");
        //startNextQ();
        return;
    }
    //console.log(body);
    console.log(itemCount);
    var page = 1 ;
    var type="ozonfirstpage";
    var is_finish = 0;
    if(itemCount < 36){
        is_finish = 1;
    }
    console.log("first_page_is_finish:"+is_finish);

    console.log("page_"+page+"_is_finish:"+is_finish);
    var type="search_follow_post";
    var firstpage=1;
    chrome.runtime.sendMessage({ data: {body,type,category,page,is_finish,firstpage,text,sku_id}, close: false });
    if(itemCount < 36 || noresult==true){
        startNextQ();
    }else{
        checkFormLoad(2,text,category,get_max_page,tf_state,itemCount,sku_id);
    }

}

function getFirstPageByAjax(dataobj,try_time){
    console.log(dataobj);
    console.log("try_time:"+try_time);
    if(!dataobj.data.q){
        console.log("no q!! no data!!")
        return;
    }
    //var url = "https://www.ozon.ru/highlight/tovary-iz-kitaya-197073/?category="+dataobj.data.cate+"&from_global=true&text="+encodeURIComponent(dataobj.data.q);
    var url = "https://www.ozon.ru/highlight/tovary-iz-kitaya-935133/?from_global=true&text="+encodeURIComponent(dataobj.data.q);

    console.log("getFirstPageByAjax_:"+url)
    var text = dataobj.data.q;
    var category = dataobj.data.cate;
    var get_max_page = dataobj.data.get_max_page
    var id = dataobj.data.id
    var sku_id = dataobj.data.sku_id
    $.ajax({
      url: url,
      method: 'GET',
      dataType: 'html',
      success: function(htmlContent) {
        // 将 HTML 页面内容解析为 DOM 元素
        const dom = $($.parseHTML(htmlContent));
        var body = "";
        var tf_state = "";
        var noresult =false;
        updateFirstPageByDom(dom,text,category,get_max_page,sku_id);
      },
      error: function(xhr, status, error) {
        console.log('Ajax error: ', error);
        if (xhr.status === 403 && status === "error") {
            var type="ozonapi403";
            chrome.runtime.sendMessage({ data: {type}, close: false });
            console.log("遇到了403错误");
             startNextQ();
            //中断
        }else{
            setTimeout(() => {
                    getFirstPageByAjax(dataobj,try_time+1)
            },try_time * 20000);
        }

      }
    });
}

function checkFormLoad(page,text,category,get_max_page,tf_state,itemCount,sku_id) {
  console.log('ajax  page='+page)
  //var urlParam= encodeURIComponent("/highlight/tovary-iz-kitaya-197073/?tf_state="+tf_state+"&from_global=true&layout_container=megapaginator&layout_page_index="+page+"&page="+page+"&text="+text+"&category="+category);
  var urlParam= encodeURIComponent("/highlight/tovary-iz-kitaya-935133/?tf_state="+tf_state+"&from_global=true&layout_container=megapaginator&layout_page_index="+page+"&page="+page+"&text="+text);

  console.log(urlParam);
  var url ="https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url="+urlParam;
  var max_page = 10;
  var max_item_count =200;
  if(get_max_page==1){
     max_page = 100;
     max_item_count =500;
  }
  console.log("cond_page:"+page+">"+max_page+"--cond_count:"+itemCount + ">"+max_item_count);
  console.log("cond_page:"+(page > max_page )+"--cond_count:"+ (itemCount > max_item_count));

  setTimeout(() => {
    $.ajax({
      url: url,
      success: (function(page){
        return function(data){

            var widgetStates = JSON.stringify(data.widgetStates);
            //console.log(widgetStates);
            if(!widgetStates || widgetStates.length < 200 ){//停止更新
                var type="search_follow_post";
                var firstpage=1;
                is_finish = 1;
                chrome.runtime.sendMessage({ data: {body,type,category,page,is_finish,text,sku_id}, close: false });
                startNextQ();
            }else{
                var body = JSON.stringify(data);
                var type="ozonlist";
                var is_finish = 0;
                for (let key in data.widgetStates) {
                    var obj = JSON.parse(data.widgetStates[key]);
                    console.log("items_size_page_"+page+":"+obj.items.length)
                    itemCount +=obj.items.length;
                    if(obj.items.length<36 || page==max_page || itemCount > max_item_count){
                        is_finish = 1;
                        break;
                    }
                }
                console.log("page_"+page+"_is_finish:"+is_finish);
                var type="search_follow_post";
                chrome.runtime.sendMessage({ data: {body,type,category,page,is_finish,text,sku_id}, close: false });
                if(is_finish==1){
                    startNextQ();
                }else{
                    checkFormLoad(page+1,text,category,get_max_page,tf_state,itemCount,sku_id);
                }
            }
        }
      })(page),
      error: function(xhr, status, error){
         console.log('ajax error page='+page)

         if (xhr.status === 403 && status === "error") {
            var type="ozonapi403";
            chrome.runtime.sendMessage({ data: {type}, close: false });
            console.log("遇到了403错误");
            //中断
            startNextQ();
        }else{
             checkFormLoad(page,text,category,get_max_page,tf_state,itemCount,sku_id);
        }

      }
    });

  }, 2000);
}

function startNextQ(){

    var type="ozonNextQAjax";
    chrome.runtime.sendMessage({ data: {type}, close: false });
        /*
    if (window.location.href.indexOf("updateozon") !== -1) {
        var type="ozonNextQAjax";
        chrome.runtime.sendMessage({ data: {type}, close: false });
    }else{
        var type="ozonNextQ";
        chrome.runtime.sendMessage({ data: {type}, close: false });
    }*/
}




function getDataDetailApiStatic(jsObject,id,goods_id){


    var data = {};
    var pics = [];
    var detail = {};

    var video = jsObject['info']['productInfo']['currentSkcImgInfo']['videoUrl'];
    var pics = jsObject['info']['productInfo']['currentSkcImgInfo']['skcImages'];


    /*var more_pic = [];
    jsObject['productIntroData']['more_goods_imgs'].forEach(item=>{
        more_pic.push(item['image_url']);
    });
    detail.more_pic = more_pic;*/

    var attr_map = {};


    jsObject['info']['productInfo']['productDescriptionInfo']['productDetails'].forEach(item=>{
        //补充属性
        attr_map[item['attr_name']] = item['attr_value'];
    });

    jsObject['info']['productInfo']['productDescriptionInfo']['completeProductDetails'].forEach(item=>{
        if(!attr_map[item['attr_name']]){
            attr_map[item['attr_name']] = item['attr_value'];
        }
    });


    var  beauty_ingredients =  jsObject['info']['productInfo']['beauty_ingredients'];

    var desc = jsObject['info']['productInfo']['productDescriptionInfo']['goods_desc'];

    var model_attr = {};

    if(jsObject['info']['productInfo']['models_info']){
        var model_info = jsObject['info']['productInfo']['models_info'];
        model_attr = model_info['attr'];
        model_attr['size'] = model_info['size'];
        model_attr['name'] = model_info['name'];
        model_attr['image'] = model_info['image'];
    }

    detail.model_attr = model_attr;
    detail.attr_map = attr_map;
    detail.attr_map = attr_map;
    detail.beauty_ingredients = beauty_ingredients;
    detail.desc = desc;
    data.pics = pics;
    data.id = id;
    data.title = jsObject['info']['productInfo']['goods_name'];
    data.skc_id = jsObject['info']['productInfo']['goods_sn'];
    data.cate_id = jsObject['info']['productInfo']['cateIds'];

    var cate_list =[];
    Object.keys(jsObject['info']['productInfo']['cateInfos']).forEach((key) => {
        cate_list.push(key);
    });
    data.cate_list = cate_list;

    //data.price = jsObject['productIntroData']['getPrice']['salePrice']['amountWithSymbol'];

    var size_list = [];
    //detail.stock = jsObject['productIntroData']['attrSizeList']['sale_attr_list'][jsObject['currentGoodsId']]['sku_list'][0]['stock']

    var size_eu_key = {};
    if(jsObject['info']['saleAttr']['multiLevelSaleAttribute']['skc_sale_attr']){

        jsObject['info']['saleAttr']['multiLevelSaleAttribute']['skc_sale_attr'].forEach(item_1=>{
            if(item_1['attr_name']=='尺寸'){
                item_1['attr_value_list'].forEach(item=>{
                    if(item['attr_value_local_size']){
                        item['attr_value_local_size'].forEach(item1=>{
                            if(item1['country_code']=='EU'){
                                size_eu_key[item['attr_value_name']] = item1['attr_local_size_value'];
                            }
                        })
                    }
                });
            }
        })
    }

    var size = {};
    size.size_eu_key = size_eu_key;

    //sml对应的尺码关系
    var size_eu_value = {};
    jsObject['info']['saleAttr']['sizeInfo']['basicAttribute']['base_code_info'].forEach(item=>{
        for (const key in item) {
            if (item.hasOwnProperty(key) && key.includes("胸罩尺寸") && key.includes("EU")) {
                size_eu_value[item['size']] = item[key];
            }
        }
    });
    size.size_eu_value = size_eu_value;
    var size_xiongwei = {};
    var size_code = {};
    jsObject['info']['saleAttr']['sizeInfo']['basicAttribute']['base_code_info'].forEach(item=>{
        size_code[item['size']] = item
        size_list.push(item['size']);
    });

    jsObject['info']['saleAttr']['sizeInfo']['multiPartInfo'].forEach(item=>{
        item['multiPartSizeInfo'].forEach(item1=>{
            delete item1.attr_id;
            delete item1.attr_name;
            delete item1.attr_value_id;
            delete item1.attr_value_name_en;

            if(size_code[item1['attr_value_name']] && Object.keys(size_code[item1['attr_value_name']]).length>0){
                Object.keys(size_code[item1['attr_value_name']]).forEach((key) => {
                    let value = size_code[item1['attr_value_name']][key];
                    item1[key] = value;
                    console.log(key,value);
                });
                size_code[item1['attr_value_name']] = item1;
            }else{
                size_code[item1['attr_value_name']] = item1;
            }
        });
    });

    var size_xie = {};
    var size_list_xie = [];
    jsObject['info']['saleAttr']['sizeInfo']['sizeInfo'].forEach(item=>{

        if(item['attr_name']=='尺寸' || item['attr_name']=='Size'){
            delete item.attr_id;
            delete item.attr_name;
            delete item.attr_value_id;
            delete item.attr_value_name_en;
            size_xie[item['attr_value_name']] = item
            size_list_xie.push(item['attr_value_name']);
        }
    });
    size.size_xie = size_xie;

    size.size_xiongwei = size_xiongwei;
    size.size_code = size_code;

    if(size_list.length===0){
        size.size_list = size_list_xie;
    }else{
        size.size_list = size_list;
    }

    //size.stock = stock;
    data.size = size;
    data.detail = detail;

    data.first_skc_id = jsObject['info']['saleAttr']['mainSaleAttribute']['info'][0]['goods_sn'];

    data.fit = "";
    data.rate = "";
    var all_color_list = [];
    jsObject['info']['saleAttr']['mainSaleAttribute']['info'].forEach(item=>{
        let new_color_url = "/"+item['goods_url_name'].replace(/ /g, '-')+"-p-"+item['goods_id']+".html";
        all_color_list.push(new_color_url);
    });
    data.all_color_list = all_color_list;

    var type = "sheindetail";
    chrome.runtime.sendMessage({ data: {type,data }, close: false })
    console.log(data);

}


function getDataDetailApi(jsObject,id,goods_id){

    var data = {};
    var pics = [];
    var detail = {};

    console.log(jsObject);
    var video = jsObject['info']['goods']['goods_imgs']['self_research_video_url'];
    jsObject['info']['goods']['goods_imgs']['detail_image'].forEach(item=>{
        if(item['origin_image']){
            pics.push(item['origin_image']);
        }else if(item['origin_image_webp']){
            pics.push(item['origin_image_webp']);
        }
    });

    var more_pic = [];
    jsObject['info']['goods']['more_goods_imgs'].forEach(item=>{
        more_pic.push(item['image_url']);
    });
    detail.more_pic = more_pic;

    var attr_map = {};
    jsObject['info']['goods']['detail']['productDetails'].forEach(item=>{
        attr_map[item['attr_name']] = item['attr_value'];
    });

    var model_attr = jsObject['info']['goods']['model']['attr'];
    if(!model_attr){
        model_attr = {};
    }
    model_attr['size'] = jsObject['info']['goods']['model']['size'];
    model_attr['name'] = jsObject['info']['goods']['model']['name'];
    model_attr['image'] = jsObject['info']['goods']['model']['image'];
    detail.model_attr = model_attr;
    detail.attr_map = attr_map;
    detail.video = video;
    data.pics = pics;
    data.id = id;
    data.title = jsObject['info']['goods']['detail']['goods_name'].trim();
    data.cate_id = jsObject['info']['goods']['detail']['supplier_top_category_id'].trim();

    var cate_list =[];
    Object.keys(jsObject['info']['goods']['parentCatsObj']).forEach((key) => {
        cate_list.push(key);
    });
    data.cate_list = cate_list;

    data.price = jsObject['info']['goods']['getPrice']['salePrice']['amountWithSymbol'];

    var size_list = [];
    var this_good_id = goods_id;
    console.log(this_good_id);
    var stock = {};
    jsObject['info']['goods']['attrSizeList']['sale_attr_list'][this_good_id]['sku_list'].forEach(item=>{
        item['sku_sale_attr'].forEach(item1=>{
            if(item1['attr_name']=='尺寸'){
                size_list.push(item1['attr_value_name']);
                stock[item1['attr_value_name']] = item['stock'];
            }
        });
    });
    detail.stock = jsObject['info']['goods']['attrSizeList']['sale_attr_list'][this_good_id]['sku_list'][0]['stock']

    var size_eu_key = {};
    if(jsObject['info']['goods']['multiLocalSize']['size_rule_list']['EU']){
        jsObject['info']['goods']['multiLocalSize']['size_rule_list']['EU'].forEach(item=>{
            size_eu_key[item['name']] = item['correspond'];
        });
    }

    var size = {};
    size.size_eu_key = size_eu_key;

    var size_jp_key = {};
    if(jsObject['info']['goods']['multiLocalSize']['size_rule_list']['JP']){
        jsObject['info']['goods']['multiLocalSize']['size_rule_list']['JP'].forEach(item=>{
            size_jp_key[item['name']] = item['correspond'];
        });
    }

    size.size_jp_key = size_jp_key;
    //sml对应的尺码关系
    var size_eu_value = {};
    jsObject['info']['goods']['sizeInfoDes']['basicAttribute']['base_code_info_other'].forEach(item=>{
        for (const key in item) {
            if (item.hasOwnProperty(key) && key.includes("胸罩尺寸") && key.includes("EU")) {
                size_eu_value[item['size']] = item[key];
            }
        }
    });
    size.size_eu_value = size_eu_value;
    var size_xiongwei = {};
    var size_code = {};
    jsObject['info']['goods']['sizeInfoDes']['basicAttribute']['base_code_info'].forEach(item=>{
        let xiongwen_item = {};
        if(item['下胸圍']){
            xiongwen_item['xia'] = item['下胸圍']
            xiongwen_item['more'] = item['胸圍 - 下胸圍差']
            size_xiongwei[item['size']] = xiongwen_item;
        }
        size_code[item['size']] = item
    });

    jsObject['info']['goods']['sizeInfoDes']['multiPartInfo'].forEach(item=>{
        item['multiPartSizeInfo'].forEach(item1=>{
            delete item1.attr_id;
            delete item1.attr_name;
            delete item1.attr_value_id;
            delete item1.attr_value_name_en;

            if(size_code[item1['attr_value_name']] && Object.keys(size_code[item1['attr_value_name']]).length>0){
                Object.keys(size_code[item1['attr_value_name']]).forEach((key) => {
                    let value = size_code[item1['attr_value_name']][key];
                    item1[key] = value;
                    console.log(key,value);
                });
                size_code[item1['attr_value_name']] = item1;
            }else{
                size_code[item1['attr_value_name']] = item1;
            }
        });
    });

    var size_xie = {};
    jsObject['info']['goods']['sizeInfoDes']['sizeInfo'].forEach(item=>{
        if(item['attr_name']=='尺寸'){
            delete item.attr_id;
            delete item.attr_name;
            delete item.attr_value_id;
            delete item.attr_value_name_en;
            size_xie[item['attr_value_name']] = item
        }
    });
    size.size_xie = size_xie;

    size.size_xiongwei = size_xiongwei;
    size.size_code = size_code;
    size.size_list = size_list;
    size.stock = stock;
    data.size = size;
    data.detail = detail;
    data.color = "";

    data.skc_id = jsObject['info']['goods']['getSeriesAndBrand']['skc'];
    jsObject['info']['goods']['detail']['mainSaleAttribute'].forEach(item=>{
        if(item['attr_name']=="颜色"){
            data.color = "顏色: "+item['attr_value'];
        }
    });

    data.first_skc_id = jsObject['info']['goods']['colorData']['colorList'][0]['goods_sn'];

    data.fit = "";
    data.rate = "";
    var all_color_list = [];
    jsObject['info']['goods']['colorData']['colorList'].forEach(item=>{
        let new_color_url = "/"+item['goods_url_name'].replace(/ /g, '-')+"-p-"+item['goods_id']+".html";
        all_color_list.push(new_color_url);
    });
    data.all_color_list = all_color_list;
    data.sale_status = $(".add-carttext-style").text().trim();

    var type = "sheindetail";
    chrome.runtime.sendMessage({ data: {type,data }, close: false })
    console.log(data);

}


function getDataDetail(jsObject,id){

    var data = {};
    var pics = [];
    var detail = {};
    //pics.push(jsObject['productIntroData']['goods_imgs']['main_image']['origin_image_webp'])

    var video = jsObject['productIntroData']['goods_imgs']['self_research_video_url'];
    jsObject['productIntroData']['goods_imgs']['detail_image'].forEach(item=>{
        if(item['origin_image']){
            pics.push(item['origin_image']);
        }else if(item['origin_image_webp']){
            pics.push(item['origin_image_webp']);
        }
    });

    var more_pic = [];
    jsObject['productIntroData']['more_goods_imgs'].forEach(item=>{
        more_pic.push(item['image_url']);
    });
    detail.more_pic = more_pic;

    var attr_map = {};
    jsObject['productIntroData']['detail']['productDetails'].forEach(item=>{
        attr_map[item['attr_name']] = item['attr_value'];
    });

    var model_attr = jsObject['productIntroData']['model']['attr'];
    if(!model_attr){
        model_attr = {};
    }
    model_attr['size'] = jsObject['productIntroData']['model']['size'];
    model_attr['name'] = jsObject['productIntroData']['model']['name'];
    model_attr['image'] = jsObject['productIntroData']['model']['image'];
    detail.model_attr = model_attr;
    detail.attr_map = attr_map;
    detail.video = video;
    data.pics = pics;
    data.id = id;
    data.title = jsObject['productIntroData']['detail']['goods_name'].trim();
    data.cate_id = jsObject['productIntroData']['detail']['supplier_top_category_id'].trim();

    var cate_list =[];
    Object.keys(jsObject['productIntroData']['parentCatsObj']).forEach((key) => {
        cate_list.push(key);
    });
    data.cate_list = cate_list;

    data.price = jsObject['productIntroData']['getPrice']['salePrice']['amountWithSymbol'];

    var size_list = [];

    var stock = {};
    jsObject['productIntroData']['attrSizeList']['sale_attr_list'][jsObject['currentGoodsId']]['sku_list'].forEach(item=>{
        item['sku_sale_attr'].forEach(item1=>{
            if(item1['attr_name']=='尺寸'){
                size_list.push(item1['attr_value_name']);
                stock[item1['attr_value_name']] = item['stock'];
            }
        });
    });
    detail.stock = jsObject['productIntroData']['attrSizeList']['sale_attr_list'][jsObject['currentGoodsId']]['sku_list'][0]['stock']

    var size_eu_key = {};
    if(jsObject['productIntroData']['multiLocalSize']['size_rule_list']['EU']){
        jsObject['productIntroData']['multiLocalSize']['size_rule_list']['EU'].forEach(item=>{
            size_eu_key[item['name']] = item['correspond'];
        });
    }

    var size = {};
    size.size_eu_key = size_eu_key;

    //sml对应的尺码关系
    var size_eu_value = {};
    jsObject['productIntroData']['sizeInfoDes']['basicAttribute']['base_code_info_other'].forEach(item=>{
        for (const key in item) {
            if (item.hasOwnProperty(key) && key.includes("胸罩尺寸") && key.includes("EU")) {
                size_eu_value[item['size']] = item[key];
            }
        }
    });
    size.size_eu_value = size_eu_value;
    var size_xiongwei = {};
    var size_code = {};
    jsObject['productIntroData']['sizeInfoDes']['basicAttribute']['base_code_info'].forEach(item=>{
        let xiongwen_item = {};
        if(item['下胸圍']){
            xiongwen_item['xia'] = item['下胸圍']
            xiongwen_item['more'] = item['胸圍 - 下胸圍差']
            size_xiongwei[item['size']] = xiongwen_item;
        }
        size_code[item['size']] = item
    });

    jsObject['productIntroData']['sizeInfoDes']['multiPartInfo'].forEach(item=>{
        item['multiPartSizeInfo'].forEach(item1=>{
            delete item1.attr_id;
            delete item1.attr_name;
            delete item1.attr_value_id;
            delete item1.attr_value_name_en;

            if(size_code[item1['attr_value_name']] && Object.keys(size_code[item1['attr_value_name']]).length>0){
                Object.keys(size_code[item1['attr_value_name']]).forEach((key) => {
                    let value = size_code[item1['attr_value_name']][key];
                    item1[key] = value;
                    console.log(key,value);
                });
                size_code[item1['attr_value_name']] = item1;
            }else{
                size_code[item1['attr_value_name']] = item1;
            }
        });
    });

    var size_xie = {};
    jsObject['productIntroData']['sizeInfoDes']['sizeInfo'].forEach(item=>{
        if(item['attr_name']=='尺寸' || item['attr_name']=='Size'){
            delete item.attr_id;
            delete item.attr_name;
            delete item.attr_value_id;
            delete item.attr_value_name_en;
            size_xie[item['attr_value_name']] = item
        }
    });
    size.size_xie = size_xie;

    size.size_xiongwei = size_xiongwei;
    size.size_code = size_code;
    size.size_list = size_list;
    size.stock = stock;
    data.size = size;
    data.detail = detail;
    data.color = "";

    data.skc_id = jsObject['rs']['detail']['goods_sn'];
    jsObject['productIntroData']['detail']['mainSaleAttribute'].forEach(item=>{
        if(item['attr_name']=="颜色"){
            data.color = "顏色: "+item['attr_value'];
        }
    });

    data.first_skc_id = jsObject['productIntroData']['colorData']['colorList'][0]['goods_sn'];

    data.fit = "";
    data.rate = "";
    var all_color_list = [];
    jsObject['productIntroData']['colorData']['colorList'].forEach(item=>{
        let new_color_url = "/"+item['goods_url_name'].replace(/ /g, '-')+"-p-"+item['goods_id']+".html";
        all_color_list.push(new_color_url);
    });
    data.all_color_list = all_color_list;
    data.sale_status = $(".add-carttext-style").text().trim();

    var type = "sheindetail";
    chrome.runtime.sendMessage({ data: {type,data }, close: false })
    console.log(data);

}




function getDataDetailPageV2(jsObject,id){

    var data = {};
    var pics = [];
    var detail = {};

    var video = jsObject['modules']['productInfo']['currentSkcImgInfo']['videoUrl'];
    var pics = jsObject['modules']['productInfo']['currentSkcImgInfo']['skcImages'];


    /*var more_pic = [];
    jsObject['productIntroData']['more_goods_imgs'].forEach(item=>{
        more_pic.push(item['image_url']);
    });
    detail.more_pic = more_pic;*/

    var attr_map = {};
    jsObject['modules']['productInfo']['productDescriptionInfo']['completeProductDetails'].forEach(item=>{
        attr_map[item['attr_name']] = item['attr_value'];
    });

    var model_attr = {};

    if(jsObject['modules']['productInfo']['models_info']){
        var model_info = jsObject['modules']['productInfo']['models_info'];
        model_attr = model_info['attr'];
        model_attr['size'] = model_info['size'];
        model_attr['name'] = model_info['name'];
        model_attr['image'] = model_info['image'];
    }

    detail.model_attr = model_attr;
    detail.attr_map = attr_map;
    detail.video = video;
    data.pics = pics;
    data.id = id;
    data.title = jsObject['modules']['productInfo']['goods_name'];
    data.skc_id = jsObject['modules']['productInfo']['goods_sn'];
    data.cate_id = jsObject['modules']['productInfo']['cateIds'];

    var cate_list =[];
    Object.keys(jsObject['modules']['productInfo']['cateInfos']).forEach((key) => {
        cate_list.push(key);
    });
    data.cate_list = cate_list;

    //data.price = jsObject['productIntroData']['getPrice']['salePrice']['amountWithSymbol'];

    var size_list = [];
    //detail.stock = jsObject['productIntroData']['attrSizeList']['sale_attr_list'][jsObject['currentGoodsId']]['sku_list'][0]['stock']

    var size_eu_key = {};
    if(jsObject['modules']['saleAttr']['multiLevelSaleAttribute']['skc_sale_attr']){

        jsObject['modules']['saleAttr']['multiLevelSaleAttribute']['skc_sale_attr'].forEach(item_1=>{
            if(item_1['attr_name']=='尺寸'){
                item_1['attr_value_list'].forEach(item=>{
                    if(item['attr_value_local_size']){
                        item['attr_value_local_size'].forEach(item1=>{
                            if(item1['country_code']=='EU'){
                                size_eu_key[item['attr_value_name']] = item1['attr_local_size_value'];
                            }
                        })
                    }
                });
            }
        })
    }

    var size = {};
    size.size_eu_key = size_eu_key;

    //sml对应的尺码关系
    var size_eu_value = {};
    jsObject['modules']['saleAttr']['sizeInfo']['basicAttribute']['base_code_info'].forEach(item=>{
        for (const key in item) {
            if (item.hasOwnProperty(key) && key.includes("胸罩尺寸") && key.includes("EU")) {
                size_eu_value[item['size']] = item[key];
            }
        }
    });
    size.size_eu_value = size_eu_value;
    var size_xiongwei = {};
    var size_code = {};
    jsObject['modules']['saleAttr']['sizeInfo']['basicAttribute']['base_code_info'].forEach(item=>{
        size_code[item['size']] = item
        size_list.push(item['size']);
    });

    jsObject['modules']['saleAttr']['sizeInfo']['multiPartInfo'].forEach(item=>{
        item['multiPartSizeInfo'].forEach(item1=>{
            delete item1.attr_id;
            delete item1.attr_name;
            delete item1.attr_value_id;
            delete item1.attr_value_name_en;

            if(size_code[item1['attr_value_name']] && Object.keys(size_code[item1['attr_value_name']]).length>0){
                Object.keys(size_code[item1['attr_value_name']]).forEach((key) => {
                    let value = size_code[item1['attr_value_name']][key];
                    item1[key] = value;
                    console.log(key,value);
                });
                size_code[item1['attr_value_name']] = item1;
            }else{
                size_code[item1['attr_value_name']] = item1;
            }
        });
    });

    var size_xie = {};
    var size_list_xie = [];
    jsObject['modules']['saleAttr']['sizeInfo']['sizeInfo'].forEach(item=>{

        if(item['attr_name']=='尺寸' || item['attr_name']=='Size'){
            delete item.attr_id;
            delete item.attr_name;
            delete item.attr_value_id;
            delete item.attr_value_name_en;
            size_xie[item['attr_value_name']] = item
            size_list_xie.push(item['attr_value_name']);
        }
    });
    size.size_xie = size_xie;

    size.size_xiongwei = size_xiongwei;
    size.size_code = size_code;

    if(size_list.length===0){
        size.size_list = size_list_xie;
    }else{
        size.size_list = size_list;
    }

    //size.stock = stock;
    data.size = size;
    data.detail = detail;

    data.first_skc_id = jsObject['modules']['saleAttr']['mainSaleAttribute']['info'][0]['goods_sn'];

    data.fit = "";
    data.rate = "";
    var all_color_list = [];
    jsObject['modules']['saleAttr']['mainSaleAttribute']['info'].forEach(item=>{
        let new_color_url = "/"+item['goods_url_name'].replace(/ /g, '-')+"-p-"+item['goods_id']+".html";
        all_color_list.push(new_color_url);
    });
    data.all_color_list = all_color_list;

    var type = "sheindetail";
    chrome.runtime.sendMessage({ data: {type,data }, close: false })
    console.log(data);

}





function getDataDetailAPiV2(jsObject,id){

    var data = {};
    var pics = [];
    var detail = {};
    //pics.push(jsObject['productIntroData']['goods_imgs']['main_image']['origin_image_webp'])

    var video = jsObject['modules']['productInfo']['currentSkcImgInfo']['videoUrl'];
    var pics = jsObject['modules']['productInfo']['currentSkcImgInfo']['skcImages'];

    /*var more_pic = [];
    jsObject['productIntroData']['more_goods_imgs'].forEach(item=>{
        more_pic.push(item['image_url']);
    });
    detail.more_pic = more_pic;*/

    var attr_map = {};
    jsObject['modules']['productInfo']['productDescriptionInfo']['productDetails'].forEach(item=>{
        attr_map[item['attr_name']] = item['attr_value'];
    });

    var model_attr = {};
    if(jsObject['modules']['productInfo']['models_info']){
        model_attr = jsObject['modules']['productInfo']['models_info']['attr'];
        model_attr['size'] = jsObject['modules']['productInfo']['models_info']['size'];
        model_attr['name'] = jsObject['modules']['productInfo']['models_info']['name'];
        model_attr['image'] = jsObject['modules']['productInfo']['models_info']['image'];
    }

    detail.model_attr = model_attr;
    detail.attr_map = attr_map;
    detail.video = video;
    data.pics = pics;
    data.id = id;
    data.title = jsObject['modules']['productInfo']['goods_name'];
    data.skc_id = jsObject['modules']['productInfo']['goods_sn'];
    data.cate_id = jsObject['modules']['productInfo']['cateIds'];

    var cate_list =[];
    Object.keys(jsObject['modules']['productInfo']['cateInfos']).forEach((key) => {
        cate_list.push(key);
    });
    data.cate_list = cate_list;

    //data.price = jsObject['productIntroData']['getPrice']['salePrice']['amountWithSymbol'];

    var size_list = [];
    //detail.stock = jsObject['productIntroData']['attrSizeList']['sale_attr_list'][jsObject['currentGoodsId']]['sku_list'][0]['stock']

    var size_eu_key = {};
    if(jsObject['modules']['saleAttr']['multiLevelSaleAttribute']['skc_sale_attr']){

        jsObject['modules']['saleAttr']['multiLevelSaleAttribute']['skc_sale_attr'].forEach(item_1=>{
            if(item_1['attr_name']=='尺寸'){
                item_1['attr_value_list'].forEach(item=>{
                    if(item['attr_value_local_size']){
                        item['attr_value_local_size'].forEach(item1=>{
                            if(item1['country_code']=='EU'){
                                size_eu_key[item['attr_value_name']] = item1['attr_local_size_value'];
                            }
                        })
                    }
                });
            }
        })
    }

    var size = {};
    size.size_eu_key = size_eu_key;

    //sml对应的尺码关系
    var size_eu_value = {};
    jsObject['modules']['saleAttr']['sizeInfo']['basicAttribute']['base_code_info'].forEach(item=>{
        for (const key in item) {
            if (item.hasOwnProperty(key) && key.includes("胸罩尺寸") && key.includes("EU")) {
                size_eu_value[item['size']] = item[key];
            }
        }
    });
    size.size_eu_value = size_eu_value;
    var size_xiongwei = {};
    var size_code = {};
    jsObject['modules']['saleAttr']['sizeInfo']['basicAttribute']['base_code_info'].forEach(item=>{
        size_code[item['size']] = item
        size_list.push(item['size']);
    });

    jsObject['modules']['saleAttr']['sizeInfo']['multiPartInfo'].forEach(item=>{
        item['multiPartSizeInfo'].forEach(item1=>{
            delete item1.attr_id;
            delete item1.attr_name;
            delete item1.attr_value_id;
            delete item1.attr_value_name_en;

            if(size_code[item1['attr_value_name']] && Object.keys(size_code[item1['attr_value_name']]).length>0){
                Object.keys(size_code[item1['attr_value_name']]).forEach((key) => {
                    let value = size_code[item1['attr_value_name']][key];
                    item1[key] = value;
                    console.log(key,value);
                });
                size_code[item1['attr_value_name']] = item1;
            }else{
                size_code[item1['attr_value_name']] = item1;
            }
        });
    });

    var size_xie = {};
    jsObject['modules']['saleAttr']['sizeInfo']['sizeInfo'].forEach(item=>{

        if(item['attr_name']=='尺寸' || item['attr_name']=='Size'){
            delete item.attr_id;
            delete item.attr_name;
            delete item.attr_value_id;
            delete item.attr_value_name_en;
            size_xie[item['attr_value_name']] = item
        }
    });
    size.size_xie = size_xie;

    size.size_xiongwei = size_xiongwei;
    size.size_code = size_code;
    size.size_list = size_list;
    //size.stock = stock;
    data.size = size;
    data.detail = detail;

    data.first_skc_id = jsObject['modules']['saleAttr']['mainSaleAttribute']['info'][0]['goods_sn'];

    data.fit = "";
    data.rate = "";
    var all_color_list = [];
    jsObject['modules']['saleAttr']['mainSaleAttribute']['info'].forEach(item=>{
        let new_color_url = "/"+item['goods_url_name'].replace(/ /g, '-')+"-p-"+item['goods_id']+".html";
        all_color_list.push(new_color_url);
    });
    data.all_color_list = all_color_list;

    var type = "sheindetail";
    chrome.runtime.sendMessage({ data: {type,data }, close: false })
    console.log(data);

}
